package cn.mengfly.testnrz.im.client;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.client.bean.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.Data;

/**
 * 保存用户状态，持有服务器连接
 *
 * @author Mengfly
 */
@Data
public class ClientSession {

    public static final AttributeKey<ClientSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");

    /**
     * 用户实现客户端会话管理的核心
     */
    private Channel channel;
    private User user;

    /**
     * 保存登录后服务端的sessionId
     */
    private String sessionId;

    private boolean isConnected = false;
    private boolean isLogin = false;

    public ClientSession(Channel channel) {
        this.channel = channel;
        this.sessionId = String.valueOf(-1);
        channel.attr(SESSION_KEY).set(this);
    }

    /**
     * 登录成功后设置sessionId
     *
     * @param ctx ctx
     * @param pkg pkg
     */
    public static void loginSuccess(ChannelHandlerContext ctx, ProtoMsg.Message pkg) {
        getSession(ctx).setSessionId(pkg.getSessionId());
        getSession(ctx).setLogin(true);
        System.out.println("登录成功");
    }

    public static ClientSession getSession(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        return channel.attr(SESSION_KEY).get();
    }

    public String getRemoteAddress() {
        return channel.remoteAddress().toString();
    }

    public ChannelFuture writeAndFlush(Object pkg) {
        return channel.writeAndFlush(pkg);
    }

    public void writeAndClose(Object pkg) {
        channel.writeAndFlush(pkg).addListener(ChannelFutureListener.CLOSE);
    }

    public void close() {
        isConnected = false;
        ChannelFuture future = channel.close();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    System.out.println("连接顺利断开了");
                }
            }
        });
    }

}
